<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog
    :title="isEdit ? '修改' : '新增'"
    :visible.sync="visible"
    :close-on-click-modal="false"
    v-dialogDrag
    append-to-body
  >
    <el-form ref="dataForm" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="类别" prop="workPositionType">
            <el-radio-group
              v-model="form.workPositionType"
              :disabled="isEdit"
              @change="updateRules"
            >
              <el-radio-button label="0">工位类型</el-radio-button>
              <el-radio-button label="1">工位</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工位类型" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="menuOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择上级工位类型"
              noOptionsText="暂无数据"
              :disabled="form.workPositionType == 0 ? true : false"
              @input="handleParentIdChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入工位/工位类别名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="工位顺序" prop="sortOrder" v-if="form.workPositionType === '1'">
        <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
      </el-form-item> -->

      <div id="app1" v-if="form.workPositionType == 1">
        <el-table class="custom-table" :data="processList" style="width: 100%">
          <el-table-column label="序号" width="80" align="center">
            <template v-slot="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="工序名称">
            <template v-slot="scope">
              <el-select v-model="scope.row.processId" placeholder="选择工序">
                <el-option
                  v-for="item in processOptions"
                  :key="item.value"
                  :label="item.processName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template v-slot="scope">
              <el-button size="mini" type="text" @click="moveUp(scope.$index)"
                >上移</el-button
              >
              <el-button size="mini" type="text" @click="moveDown(scope.$index)"
                >下移</el-button
              >
              <el-button
                size="mini"
                type="text"
                style="color: red"
                @click="deleteProcess(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 20px" @click="addRow"
          >添加行</el-button
        >
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fetchMenuTree, addObj, putObj, getObj } from "@/api/pfoc/workposition";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { fetchList } from "@/api/pfoc/pfocprocess";

export default {
  name: "workPositionForm",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单树选项
      menuOptions: [],
      // 是否显示弹出层
      visible: false,
      // 查询参数
      queryParams: {
        workPositionType: "0",
      },
      form: {
        id: undefined, //工位ID
        parentId: undefined, //父级ID
        name: null, //工位类名称
        workPositionType: null, //类别
        workPositionName: null, //工位名
        sortOrder: undefined, //工位顺序
      },
      flg: false, //是否可选工位类别
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: "工位/工位类型名称不能为空",
            trigger: "blur",
          },
        ],
        workPositionType: [
          { required: true, message: "请选择添加的类别", trigger: "blur" },
        ],
        sortOrder: [
          { required: true, message: "工位顺序不能为空", trigger: "blur" },
        ],
        parentId: [],
      },
      processList: [
        {
          processId: "", //工序id
          processName: "", //工序名称
          sortOrder: 0, //排序值
        },
      ],
      processOptions: [
        { value: "来料检验", label: "来料检验" },
        { value: "剥纤", label: "剥纤" },
        { value: "穿纤", label: "穿纤" },
        { value: "其他工序", label: "其他工序" },
      ],
      process: [],
      isEdit: false,
    };
  },
  watch: {
    "form.parentId": function (newVal, oldVal) {
      // 判断当前是否是作业新增
      if (
        this.form.workPositionType === "1" &&
        this.validatenull(this.form.id)
      ) {
        //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
        if (this.form.parentId !== -1 && this.form.parentId !== undefined) {
          //获取当前选中节点下有多少数据
          this.form.sortOrder =
            this.countLeaves(this.menuOptions, this.form.parentId) + 1;
        }
      }
    },
  },
  created() {
    this.getpfocprocess();
  },
  methods: {
    getpfocprocess() {
      fetchList({ current: 1, size: 999 }).then((response) => {
        this.processOptions = response.data.data.records;
        console.log(response);
      });
    },
    moveUp(index) {
      if (index > 0) {
        const temp = this.processList[index];
        this.processList.splice(index, 1);
        this.processList.splice(index - 1, 0, temp);
      }
    },
    moveDown(index) {
      if (index < this.processList.length - 1) {
        const temp = this.processList[index];
        this.processList.splice(index, 1);
        this.processList.splice(index + 1, 0, temp);
      }
    },
    deleteProcess(index) {
      this.processList.splice(index, 1);
    },
    addRow() {
      this.processList.push({
        processId: "", //工序id
        processName: "", //工序名称
      });
    },
    init(isEdit, id, workPositionType) {
      this.isEdit = isEdit;
      console.log(111, this.isEdit);

      this.processList = [
        {
          processId: "", //工序id
          processName: "", //工序名称
          sortOrder: 0, //排序值
        },
      ];
      this.visible = true;
      this.getTreeselect();
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.form.sortOrder = undefined;
        this.form.parentId = id;
        this.form.workPositionType = workPositionType;
        this.flg =
          !this.validatenull(workPositionType) && !this.validatenull(id);
        if (isEdit) {
          getObj(id).then((response) => {
            this.form = Object.assign(
              {},
              this.form,
              Object.fromEntries(
                Object.entries(response.data.data).filter(
                  ([key]) => key in this.form
                )
              )
            ); //防止为form新增属性，如createTime等，此方法只给form中存在的属性赋值

            if (response.data.data.workPositionProcessList.length != 0) {
              this.processList = response.data.data.workPositionProcessList;
            }

            if (this.form.workPositionType === "1") {
              this.form.name = this.form.workPositionName;
            }
          });
        } else {
          this.form.id = undefined;
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (this.validatenull(this.form.parentId)) {
            this.form.parentId = -1;
          }
          if (this.form.workPositionType === "1") {
            this.form.workPositionName = this.form.name;
            const selectedItem = this.findNodeById(
              this.menuOptions[0].children,
              this.form.parentId
            );
            this.form.name = selectedItem.label;

            this.process = this.processList.map((item, index) => {
              return {
                ...item,
                sortOrder: index,
                processName: this.processOptions.find(
                  (i) => i.id === item.processId
                ).processName,
              };
            });
          } else {
            this.form.workPositionName = null;
          }

          let params = {
            ...this.form,
            workPositionProcessList: this.process,
          };

          if (this.form.id) {
            console.log(params);
            putObj(params).then((data) => {
              this.$message.success("修改成功");
              this.visible = false;
              this.$emit("refreshDataList");
            });
          } else {
            console.log(params);
            addObj(params).then((data) => {
              this.$message.success("添加成功");
              this.visible = false;
              this.$emit("refreshDataList");
            });
          }
        }
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      //创建对象
      fetchMenuTree().then((response) => {
        this.menuOptions = [];
        const menu = { id: -1, name: "根", children: [] };
        menu.children = response.data.data;
        this.menuOptions.push(menu);
        // 判断当前是否是作业新增
        if (
          this.form.workPositionType === "1" &&
          this.validatenull(this.form.id)
        ) {
          //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
          if (this.form.parentId !== -1 && this.form.parentId !== undefined) {
            //获取当前选中节点下有多少数据
            this.form.sortOrder =
              this.countLeaves(this.menuOptions, this.form.parentId) + 1;
          }
        }
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      if (node.workPositionType === "1") {
        return {
          id: node.id,
          label: null,
          children: node.children,
        };
      } else {
        return {
          id: node.id,
          label: node.name,
          children: node.children,
        };
      }
    },
    /** 动态更新表单校验规则 */
    updateRules() {
      if (this.form.workPositionType === "1") {
        this.form.parentId = undefined;
        this.rules.parentId = [
          { validator: this.validateParentId, trigger: "blur" },
        ];
      } else {
        this.rules.parentId = [];
        this.form.sortOrder = undefined;
        this.form.parentId = -1;
      }
      this.$refs["dataForm"].clearValidate("parentId");
    },
    /** 自定义校验规则 */
    validateParentId(rule, value, callback) {
      if (
        this.form.workPositionType === "1" &&
        (this.form.parentId === undefined || this.form.parentId === -1)
      ) {
        callback(new Error("请选择有效的上级工位类型"));
      } else {
        callback();
      }
    },
    /** 在选择完符合产品类别的数据时重新校验 parentId */
    handleParentIdChange(value) {
      if (this.form.parentId !== undefined && this.form.parentId !== -1) {
        this.$refs["dataForm"].clearValidate("parentId");
      } else {
        this.$refs["dataForm"].validateField("parentId");
      }
    },
    //递归函数
    findNodeById(tree, id) {
      for (let node of tree) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findNodeById(node.children, id);
          if (foundNode) {
            return foundNode;
          }
        }
      }
      return null;
    },
    // 获取当前选中节点下有多少数据
    countLeaves(options, selectedId) {
      let count = 0;

      function traverse(nodes) {
        nodes.forEach((node) => {
          if (node.id === selectedId) {
            if (node.children) {
              node.children.forEach((child) => {
                if (!child.children) {
                  count++;
                }
              });
            }
          } else if (node.children) {
            traverse(node.children);
          }
        });
      }

      traverse(options);
      return count;
    },
  },
};
</script>
<style lang="less" scoped>
.custom-table .el-table th {
  background: #f8f9fa !important;
  color: #333;
  font-weight: 600;
}
.custom-table .el-button {
  margin-right: 8px;
}
::v-deep .el-table th {
  background-color: #f6f8fa !important;
}
</style>
